package com.nowcoder.community.service;

import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

/**
 * <p>Title: LikeService</p>
 * <p>author 12427</p>
 *
 * @version ver1.0
 * @date 2022/8/19 15:21
 */

@Service
public class LikeService {

    @Autowired
    private RedisTemplate redisTemplate ;


    // 点赞

    /**
     *
     * @param userId  点赞者的ID
     * @param entityType
     * @param entityId
     * @param entityUserId  被赞者的ID
     */
    public void like(int userId , int entityType , int entityId  , int entityUserId){
//        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType ,entityId) ;
//        Boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
//
//        if(isMember){
//            redisTemplate.opsForSet().remove(entityLikeKey , userId) ;
//        }else{
//            redisTemplate.opsForSet().add(entityLikeKey,userId) ;
//        }
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType ,entityId) ;
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId) ; // 作者

                // 先查询当前用户是否点过赞
                Boolean isMember = operations.opsForSet().isMember(entityLikeKey, userId);

                // 查询写在事务之外
                operations.multi();
                // 事务开始
                if(isMember){
                    // 当前页面移除赞
                    operations.opsForSet().remove(entityLikeKey , userId) ;
                    // 被赞人的获赞数减一
                    operations.opsForValue().decrement(userLikeKey) ;
                }else{
                    operations.opsForSet().add(entityLikeKey,userId) ;
                    operations.opsForValue().increment(userLikeKey) ;
                }

                return operations.exec();
            }
        }) ;

    }

    // 查询某实体的点赞数量
    public long findEntityLikeCount(int entityType , int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType ,entityId) ;
        return redisTemplate.opsForSet().size(entityLikeKey) ;
    }

    // 查询某人对实体的点赞状态
    public int findEntityLikeStatus(int userId , int entityType , int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType ,entityId) ;
        // 1 赞 0 没有赞
        return redisTemplate.opsForSet().isMember(entityLikeKey , userId)? 1 : 0 ;
    }

    // 查询某用户获得赞的数量
    public int findUserLikeCount(int userId){
        String userLikeKey = RedisKeyUtil.getUserLikeKey(userId) ;
        Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count == null ? 0 : count.intValue() ;
    }

}

